from datetime import datetime

import jwt

from cfg.model.UserModel import UserModel

secret_key_str = "dashdwqe0hno123dalsdk90123maslnxdio"
expiration_time_in_seconds = 60 * 60 * 2


# 生成Token
def generate_token(data: UserModel):
    return "Bearer " + jwt.encode(payload={
        "id": data.id,
        "username": data.username
    }, key=secret_key_str, algorithm='HS256')


# 验证Token
def verify_token(token_str):
    try:
        token_str = token_str.replace("Bearer ", "")
        data = jwt.decode(token_str, secret_key_str, algorithms=['HS256'])
        return data
    except jwt.ExpiredSignatureError:
        # Token已过期
        return None
    except jwt.InvalidTokenError:
        # Token无效
        return None
